import { WebGLCanvas } from "@nirvana/canvas";
import {
  AmbientLight,
  BallGeometry,
  Camera,
  Data,
  DataElement,
  Geometry,
  Mesh,
  PointLight,
  SceneNode,
  ShaderMaterial
} from "@nirvana/core";
import { Color, Vector3 } from "@nirvana/math";
import { Shader } from "@nirvana/shaders";

async function main() {
  let canvas = document.getElementById("engine-nirvana");
  const webCanvas = new WebGLCanvas(canvas, {
    rate: 1
  });
  const engine = webCanvas.engine;

  const scene = engine.sceneManager.createScene("root");
  const camera = new Camera("", engine);
  scene.addCamera(camera);
  camera.transform.setPosition(0, 0, 20);
  const rootEntity = new SceneNode("root-entity");
  scene.addEntity(rootEntity);

  const ambLight = new AmbientLight("alight");
  ambLight.color.set(1, 1, 1, 1);
  scene.addLight(ambLight);

  const vs = `
  attribute vec4 POSITION;
  attribute vec3 NORMAL;
  attribute vec2 TEXCOORD_0;

  uniform vec4 COLOR;

  // uniform mat4 u_localMat;
  uniform mat4 u_modelMat;
  uniform mat4 u_viewMat;
  uniform mat4 u_projMat;
  uniform mat4 u_MVMat;
  // uniform mat4 u_MVPMat;
  // uniform mat4 u_normalMat;
  // uniform vec3 u_cameraPos;

  varying vec3 v_position;
  varying vec3 v_normal;
  varying vec4 v_color;
  varying vec2 v_uv0;

  void main() {
    gl_Position = u_projMat * u_viewMat * u_modelMat * POSITION;

    v_position = (u_modelMat * POSITION).xyz;
    v_normal = mat3(u_MVMat) * NORMAL;
    v_color = COLOR;
    v_uv0 = TEXCOORD_0;
  }
  `;
  const fs = `
  uniform mat4 u_localMat;
  uniform mat4 u_modelMat;
  uniform mat4 u_viewMat;
  uniform mat4 u_projMat;
  uniform mat4 u_MVMat;
  uniform mat4 u_MVPMat;
  uniform mat4 u_invMat;
  uniform mat4 u_normalMat;
  uniform vec3 u_cameraPos;

  uniform vec3 u_AMBIENTLIGHT_COLOR;

  varying vec3 v_position;
  varying vec3 v_normal;
  varying vec4 v_color;

  void main() {
    vec4  destColor = v_color * vec4(u_AMBIENTLIGHT_COLOR, 1.0);
    gl_FragColor = destColor;
    
  }
`;

  const shader = Shader.create("light-demo", vs, fs);
  const material = new ShaderMaterial("", shader);
  material.shaderData.setColor("COLOR", new Color(0.25, 0.25, 0.75, 1.0));

  const gem = new BallGeometry(2, 64, 64);

  rootEntity.addChildNode(new Mesh(gem, material));

  engine.update = () => {
    rootEntity.transform.translate(0, 0, -0.01);
    rootEntity.transform.rotate(0, -0.01, 0);
  };
}

main();
